package com.hs.room.repository

import android.content.Context
import com.hs.room.AppDatabase
import com.hs.room.model.archive.ArchiveLevel
import com.hs.room.model.archive.ArchiveStatus
import com.hs.room.model.archive.ArchiveType
import com.hs.room.repository.service.IArchiveDictRepository
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.emitAll
import kotlinx.coroutines.flow.flow
import javax.inject.Inject

/**
 * 档案字典仓库 类型、级别、状态
 */
class ArchiveDictRepository @Inject constructor(
    @ApplicationContext var context: Context,
    val db: AppDatabase
) : IArchiveDictRepository {
    override suspend fun insert(d: ArchiveType) {
        db.archiveTypeDao().insert(d)
    }

    override suspend fun insert(d: ArchiveStatus) {
        db.archiveStatusDao().insert(d)
    }

    override suspend fun insert(d: ArchiveLevel) {
        db.archiveLevelDao().insert(d)
    }

    override suspend fun update(d: ArchiveType) {
        db.archiveTypeDao().update(d)
    }

    override suspend fun update(d: ArchiveStatus) {
        db.archiveStatusDao().update(d)
    }

    override suspend fun update(d: ArchiveLevel) {
        db.archiveLevelDao().update(d)
    }

    override fun getType(limit: Int, offset: Int): Flow<List<ArchiveType>> {
        return flow {
            emitAll(db.archiveTypeDao().get(offset, offset * limit))
        }.catch { e ->
            // 进行异常处理
            println("Error occurred while fetching getType data: $e")
        }
    }

    override fun getLevel(limit: Int, offset: Int): Flow<List<ArchiveLevel>> {
        return flow {
            emitAll(db.archiveLevelDao().getAll())
        }.catch { e ->
            // 进行异常处理
            println("Error occurred while fetching getLevel data: $e")
        }
    }

    override fun getStatus(limit: Int, offset: Int): Flow<List<ArchiveStatus>> {
        return flow {
            emitAll(db.archiveStatusDao().getAll())
        }.catch { e ->
            // 进行异常处理
            println("Error occurred while fetching getStatus data: $e")
        }
    }

    override fun countType(): Int {
        return db.archiveTypeDao().count()
    }

    override fun countLevel(): Int {
        return db.archiveLevelDao().count()
    }

    override fun countStatus(): Int {
        return db.archiveStatusDao().count()
    }

    override suspend fun delete(d: ArchiveType) {
        db.archiveTypeDao().delete(d)
    }

    override suspend fun delete(d: ArchiveStatus) {
        db.archiveStatusDao().delete(d)
    }

    override suspend fun delete(d: ArchiveLevel) {
        db.archiveLevelDao().delete(d)
    }
}